// indent.js
var app = getApp();
var QR = require("../../../common/qrcode.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    reason: "",
    placeholder: 'http://www.hn96520.com/',
    disabled: false,
    hint: false,
    appColor: app.appColor
  },
  onReady: function() {
    var size = this.setCanvasSize();
    var initUrl = this.data.ordercode;
    this.createQrCode(initUrl, "mycanvas", size.w, size.h);
  },

  //适配不同屏幕大小的canvas
  setCanvasSize: function() {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 150 / 75;
      var width = res.windowWidth / scale;
      var height = width;
      size.w = width;
      size.h = height;
    } catch (e) {
      console.log("获取设备信息失败" + e);
    }
    return size;
  },

  createQrCode: function(url, canvasId, cavW, cavH) {
    QR.qrApi.draw(this.data.ordercode, canvasId, cavW, cavH);
  },

  qrcode: function(code) {
    var that = this;
    var st = setTimeout(function() {
      wx.hideToast()
      var size = that.setCanvasSize();
      //绘制二维码
      that.createQrCode(code, "mycanvas", size.w, size.h);
      clearTimeout(st);
    }, 500)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    app.showLoadings();
    let that = this;
    if (options.ordercode) {
      this.setData({
        ordercode: options.ordercode,
        phone: app.HandsetNumber,
        orderType: options.issharing == 'true' ? '拼车' : '包车',
      });
      this.message(options.ordercode);
    } else {
      wx.getStorage({
        key: 'newOrderMess',
        success: function(res) {
          that.message(res.data.data.OrderCode);
          that.setData({
            ordercode: res.data.data.OrderCode,
            orderType: options.issharing == 'true' ? '拼车' : '包车',
            phone: app.HandsetNumber,
          });
        },
      });
    }
  },

  // 提示框定时器
  hintTime: function (that) {
    let num = 2;
    const time = setInterval(function () {
      if (num <= 0) {
        that.setData({ hint: false });
        return;
      }
      num--;
    }, 1000)
  },

  message: function(ordercode) {
    var that = this;
    wx.request({
      url: app.serviceurl + 'CarRental/CarRentalQueryOrderDetail',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {
        OrderCode: ordercode
      },
      dataType: 'json',
      success: function(res) {
        if (res.data.Takeman != null && typeof(res.data.Takeman) != undefined) {
          res.data.Takeman.forEach(function(item) {
            item.CardID = item.CardID.replace(/(\d{6})\d{4}(\d{4})/, '$1****$2');
          });
        }
        that.setData({
          data: res.data,
          reason: res.data.CannotRefundReason ? res.data.CannotRefundReason : ""
        });
        if (res.data.DriverAndCar) {
          that.setData({
            names: res.data.DriverAndCar.Name,
          });
        };

        app.hideLoadings();
      },
      fail: function(res) {
        app.hideLoadings();
      }
    })
  },

  QRcodes: function() {
    wx.navigateTo({
      url: '../../../pages/QRcode/QRcode?code=' + this.data.ordercode,
    })
  },

  // 取消订单
  abandon: function() {
    var that = this;
    wx.showModal({
      title: '确认取消',
      content: '确定取消该订单吗？',
      confirmText: "确定",
      cancelText: "放弃",
      success: function(res) {
        if (res.confirm) {
          app.carHint = false;
          wx.request({
            url: app.serviceurl + 'CarRental/CarRentalCancleOrder',
            header: {
              Authorization: "Bearer " + app.accesstoken
            },
            data: {
              OrderCode: that.data.ordercode
            },
            dataType: 'json',
            success: function(res) {
              that.message(that.data.ordercode)
            },
            fail: function(res) {
              console.log(res)
            },
            complete: function(res){
              that.setData({
                hintMessage: res.data.Message.length > 0 ? res.data.Message : '取消成功',
                hint: true
              })
              that.hintTime(that)
            }
          })
        } else {

        }
      }

    });
  },

  openToast: function() {
    wx.showToast({
      title: '支付完成',
      icon: 'success',
      duration: 600
    });
  },

  fail: function() {
    wx.showToast({
      title: '支付失败',
      icon: 'success',
      duration: 600
    });
  },

  // 支付未完成订单
  wxpay: function(e) {
    this.setData({
      disabled: true
    })
    var that = this;
    var OrderCode = e.currentTarget.dataset.indent;
    wx.request({
      url: app.serviceurl + 'CarRental/CarRentalPayOrder',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {
        OrderCode: this.data.ordercode
      },
      dataType: 'json',
      success: function(res) {
        if (!res.data.Result) {
          that.fail();
          return
        };
        if (res.data.Result) {
          wx.requestPayment({
            timeStamp: res.data.timeStamp,
            nonceStr: res.data.nonceStr,
            package: res.data.package,
            signType: res.data.signType,
            paySign: res.data.paySign,
            success: function(resr) {
              if (resr.errMsg == "requestPayment:ok") {
                //支付成功
                that.openToast();
                that.message();
                var orderId = e.currentTarget.dataset.indent;
              }
            }
          })
        } else {
          wx.showToast({
            title: '调起支付失败',
          })
        }
      },
      fail: function(res) {
        console.log(res)
      },
      complete: function() {
        var time = setTimeout(function() {
          that.setData({
            disabled: false
          });
        }, 1000)
      }
    })
  },

  // 位置信息
  location: function(e) {
    var stand = e.currentTarget.dataset.stand,
      lat = e.currentTarget.dataset.lat,
      long = e.currentTarget.dataset.long;

    wx.openLocation({
      latitude: lat,
      longitude: long,
      scale: 14,
      name: stand,
    })
  },

  openConfirm: function() {
    wx.navigateTo({
      url: '../refund/refund?code=' + this.data.ordercode + '&y=' + true,
    })
  },
  refundreson: function() {
    try {
      wx.showModal({
        content: this.data.reason,
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      });
    } catch (err) {}
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.qrcode(this.data.ordercode);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  position: function(e) {
    wx.navigateTo({
      url: '../../../customline/lookdriverposition/lookdriverposition?name=' + this.data.names + '&ordercode=' + this.data.ordercode
    })
  }

})